package com.opennetexam.manager.controller;

import com.opennetexam.manager.common.CommonFunction;
import com.opennetexam.manager.common.OperationResult;
import com.opennetexam.manager.common.ReturnData;
import com.opennetexam.manager.databasemodel.ExamApp;
import com.opennetexam.manager.databasemodel.ExamSite;
import com.opennetexam.manager.dto.AdminInfo;
import com.opennetexam.manager.dto.ExamAdminInfoDTO;
import com.opennetexam.manager.dto.ExamInfo;
import com.opennetexam.manager.enums.OperationResultType;
import com.opennetexam.manager.utils.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author naicha
 * Created on 2017/11/7.
 */
@Controller
@RequestMapping(value = "/Login")
public class LoginController extends BaseController{

    private static Logger logger = Logger.getLogger(LoginController.class);

    @Value("${key}")
    private String key;
    @Value("${isNeedCheckVersion}")
    private String isNeedCheckVersion;
    @Value("${ExamSiteURL}")
    private String examSiteURL;

    /**
     * 登录页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/Index")
    public String index(Map<String,Object> model){
        model.put("IsNeedCheckVersion",isNeedCheckVersion);
        return "login/Index";
    }

    /**
     * 注销
     * @return
     */
    @RequestMapping(value = "/Logout")
    public String logout(String account){
        ExamAdminInfoDTO adminUserInfo = getAdminUserInfo(account);
        if(adminUserInfo != null){
            logOut(account);
        }
        return "redirect:Index";
    }

    /**
     * 测试网络连接，和指定的url连接是否正常，默认尝试连接5秒
     * @param serverUrl 网考服务地址
     */
    @RequestMapping(value = "/ConnectTest",method = RequestMethod.POST)
    public void connectTest(String serverUrl,HttpServletResponse response){
        Boolean result = InternetHelper.IsHostAlive(serverUrl);
        CommonFunction.responseWrite(response,result);
    }

    /**
     * 验证服务器路径、验证码
     * @return
     */
    @RequestMapping(value = "/Verification",method = RequestMethod.POST)
    public void verification(@RequestBody Map<String,String> requestBody, HttpServletResponse response){
        String validateCode = requestBody.get("validateCode");
        String batchCode = requestBody.get("batchCode");

        try {
            //String result = HttpRequestUtils.sendGet(examSiteURL + "examplan/exampoint?siteCode=" + validateCode+"&batchCode="+batchCode, null);

            String result = HttpRequestUtils.sendGet(examSiteURL + "examplan/exampoint?siteCode=" + validateCode, null);
            ReturnData returnData = GsonUtil.fromJsonToObject(result, ReturnData.class);
            if(StringUtils.isEmpty(result)){
                OperationResult operationResult = new OperationResult(OperationResultType.Warning, returnData.getMessage());
                CommonFunction.responseWrite(response,operationResult);
            }else if(!returnData.getSuccess()){
                OperationResult operationResult = new OperationResult(OperationResultType.Warning, returnData.getMessage());
                CommonFunction.responseWrite(response,operationResult);
            }else{
                ExamInfo examInfo = GsonUtil.fromJsonToObject(returnData.getPayload(), ExamInfo.class);
                ExamApp examApp = new ExamApp();
                examApp.setAppID(examInfo.getAppId());
                examApp.setAppName(examInfo.getAppName());

                ExamSite examSite = new ExamSite();
                examSite.setExamSiteID(examInfo.getExamSiteId());
                examSite.setExamSiteCode(examInfo.getExamSiteCode());
                examSite.setExamSiteName(examInfo.getExamSiteName());
                examSite.setSitePwd("");

                Map<String, Object> returnMap = new HashMap<>(4);
                returnMap.put("resultType", OperationResultType.Success);
                returnMap.put("app", examApp);
                returnMap.put("site", examSite);
                CommonFunction.responseWrite(response,returnMap);
            }
        }catch (Exception e){
            CommonFunction.responseWrite(response,new OperationResult(OperationResultType.Error,"获取考点数据失败"));
            logger.error("获取考点数据失败",e);
        }
    }

}
